package org.hadoop.zk;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
public class ZkDownload {
    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            System.out.println("用法：java cn.zk.ZkDownload <zk集群地址> <zk节点路径> [保存文件名]");
            return;
        }
        String zkServer = args[0];
        String path = args[1];
        String dest = null;
        if (args.length >= 3) {//如果传递了第三个参数，即保存的文件
            dest = args[2];
        }
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper(zkServer, 3000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();
        Stat stat = zooKeeper.exists(path, null);
        if (stat == null) {
            throw new RuntimeException("节点:" + path + "不存在!");
        }
        byte[] bs = zooKeeper.getData(path, false, stat);
        if (dest != null) {
            path = dest;
        } else {
            path = path.substring(path.lastIndexOf("/") + 1);//只取出最后一个节点的名称
        }
        OutputStream out = new FileOutputStream(path);
        out.write(bs);
        out.close();
        System.out.println("下载完成");
    }
}
